<template>
  <div class="app-container" style="height: 100%">
    <div class="app-container-inner user-import">
      <div class="btns_btn">
        <HPlainButton @click="downloadExcelTemplate(`${routeTitle}模板.xlsx`)"
          >下载模版</HPlainButton
        >
        <div class="dialog-btn">
          <!--工单模块-->
          <el-select
            v-if="routeTitle === '物料资料导入'"
            v-model="goodType"
            style="width: 160px; height: 30px"
            clearable
            placeholder="请选择物料类型"
          >
            <el-option label="成品" :value="1" />
            <el-option label="物料" :value="2" />
          </el-select>
          <HPlainButton :disabled="fileList.length == 0" @click="onConfirmUploadBtnClick"
            >确认上传</HPlainButton
          >
          <HButton :disabled="isUploading" @click="onCancelBtnClick">关闭</HButton>
        </div>
      </div>

      <!-- 上传组件 -->
      <el-upload
        ref="upload"
        v-model:file-list="fileList"
        class="upload_xy"
        accept=".xls, .xlsx"
        :auto-upload="false"
        drag
        :show-file-list="false"
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="handleChange"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text"> 拖动文件到这 或 <em>点击上传</em> </div>
      </el-upload>

      <!-- 文件列表 -->
      <div class="files">
        <div v-for="(file, fileIndex) in fileList" :key="fileIndex" class="file">
          <div class="txt">{{ file.name }}</div>
          <i class="iconfont icon-del" @click="onRemoveFileBtnClick"></i>
        </div>
      </div>

      <!-- 进度条 -->
      <div v-if="dataReturned && !dataReturned.end" class="process_bar_container">
        <el-progress color="#00c0c0" :percentage="syncProgress" type="dashboard" :stroke-width="10">
          <span class="percentage">{{ syncProgress.toFixed(2) }}%</span>
          <span class="tip">数据正在导入中，请稍后...&nbsp;...</span>
        </el-progress>
      </div>

      <!-- 数据全部导入成功的提示 -->
      <div
        v-if="dataReturned && dataReturned.end && dataReturned.importFailtDataList.length === 0"
        class="import-success"
      >
        <!-- 数据统计 - 这是无失败数据时的统计 - 用于控制样式 -->
        <div class="statistics success-statistics">
          总计
          <span>{{ dataReturned.totalCount }}</span>
          条数据，上传成功
          <span class="success_num">{{ dataReturned.totalCount - errorList.length }}</span>
          条，失败
          <span class="fail_num">{{ errorList.length }}</span>
          条
        </div>
        <div class="circle-wrapper">
          <div class="circle-bg">
            <i class="iconfont icon-dagou"></i>
          </div>
          <div class="text">全部数据导入完成！</div>
        </div>
        <div class="placeholder"></div>
      </div>

      <!-- 导入失败的数据 -->
      <div
        v-if="dataReturned && dataReturned.end && dataReturned.importFailtDataList.length > 0"
        class="import_fail_data_container"
      >
        <div class="title-wrapper">
          <div class="text"> 导入失败数据列表 </div>
          <!-- 数据统计 - 这是有失败数据时的统计 - 用于控制样式 -->
          <div class="statistics">
            总计
            <span>{{ dataReturned.totalCount }}</span>
            条数据，上传成功
            <span class="success_num">{{ dataReturned.totalCount - errorList.length }}</span>
            条，失败
            <span class="fail_num">{{ errorList.length }}</span>
            条
          </div>
        </div>

        <!-- 物料资料导入失败的数据 -->
        <el-table
          v-if="route.name === 'goodsExcelImport'"
          id="el-table"
          border
          class="tableError_list"
          stripe
          resizable
          :data="dataReturned.importFailtDataList"
        >
          <el-table-column type="index" label="序号" width="55" fixed :align="'center'" />
          <el-table-column show-overflow-tooltip prop="excelRowNum" label="excel行号" width="80" />
          <el-table-column show-overflow-tooltip prop="excelMsg" label="导入失败原因" width="130" />
          <el-table-column
            show-overflow-tooltip
            prop="goodsName"
            label="物料名称"
            min-width="200"
            fixed
          />
          <el-table-column show-overflow-tooltip prop="type" label="物料类型" width="150" />
          <el-table-column show-overflow-tooltip prop="goodsBrand" label="物料品牌" width="150" />
          <el-table-column show-overflow-tooltip prop="goodsModel" label="物料型号" width="150" />
          <el-table-column show-overflow-tooltip prop="goodsCode" label="物料编号" width="150" />
          <el-table-column
            show-overflow-tooltip
            prop="goodsItemNumber"
            label="物料货号"
            width="150"
          />
          <el-table-column show-overflow-tooltip prop="goodsType" label="物料分类" width="150" />
          <el-table-column
            show-overflow-tooltip
            prop="goodsSpecName"
            label="物料规格"
            width="150"
          />
          <el-table-column show-overflow-tooltip prop="goodsUnit" label="物料单位" width="150" />
          <el-table-column show-overflow-tooltip prop="price" label="单价" width="150" />
          <el-table-column show-overflow-tooltip prop="warrantDay" label="质保周期" width="150" />
          <el-table-column label="是否为核心件" width="150" prop="coreMaterials" />
        </el-table>

        <!-- 客户资料导入失败的数据 -->
        <el-table
          v-if="route.name === 'userExcelImport'"
          id="el-table"
          border
          class="tableError_list"
          stripe
          resizable
          :data="dataReturned.importFailtDataList"
        >
          <el-table-column type="index" label="序号" width="55" fixed :align="'center'" />
          <el-table-column prop="excelRowNum" label="excel行号" width="80" />
          <el-table-column show-overflow-tooltip prop="excelMsg" label="导入失败原因" width="240" />
          <el-table-column show-overflow-tooltip prop="code" label="客户序列号" width="130" />
          <el-table-column
            show-overflow-tooltip
            prop="username"
            label="客户联系人姓名"
            width="130"
          />
          <el-table-column show-overflow-tooltip prop="phone" label="联系人手机号" width="130" />
          <el-table-column show-overflow-tooltip prop="province" label="客户地址-省" width="130" />
          <el-table-column show-overflow-tooltip prop="city" label="客户地址-市" width="130" />
          <el-table-column show-overflow-tooltip prop="area" label="客户地址-县/区" width="130" />
          <el-table-column show-overflow-tooltip prop="address" label="客户详细地址" width="130" />
          <el-table-column show-overflow-tooltip prop="userType" label="客户分类" width="130" />
          <el-table-column
            show-overflow-tooltip
            prop="selectknowledgeAuthor"
            label="知识库查看权限"
            width="130"
          >
            <template #default="scope">
              <span v-if="scope.row.selectknowledgeAuthor">根据权限查看</span>
              <span v-else>查看所有</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="level" label="客户等级" width="130" />
        </el-table>

        <!-- 工程师资料导入失败的数据 -->
        <el-table
          v-if="route.name === 'empExcelImport'"
          id="el-table"
          border
          class="tableError_list"
          stripe
          resizable
          :data="dataReturned.importFailtDataList"
        >
          <el-table-column type="index" label="序号" width="55" fixed :align="'center'" />
          <el-table-column prop="excelRowNum" label="excel行号" width="80" />
          <el-table-column show-overflow-tooltip prop="excelMsg" label="导入失败原因" width="240" />
          <el-table-column
            show-overflow-tooltip
            label="工程师姓名"
            prop="username"
            min-width="220"
          />
          <el-table-column
            show-overflow-tooltip
            label="工程师手机号"
            prop="phone"
            min-width="120"
          />
          <el-table-column show-overflow-tooltip prop="superManager" label="角色管理" width="120">
            <template #default="scope">
              {{ scope.row.superManager ? '管理员' : '工程师' }}
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="工程师等级"
            prop="networkEmpLevel"
            min-width="120"
          />
          <el-table-column
            show-overflow-tooltip
            label="工程师分类"
            prop="networkEmpType"
            min-width="120"
          />
          <el-table-column show-overflow-tooltip label="所属部门" prop="network" min-width="300" />
          <el-table-column
            show-overflow-tooltip
            label="工程师技能"
            prop="networkEmpSkill"
            min-width="120"
          />
        </el-table>

        <!-- 工单资料导入失败的数据 -->
        <el-table
          v-if="route.name === 'orderExcelImport'"
          id="el-table"
          border
          class="tableError_list"
          stripe
          resizable
          :data="dataReturned.importFailtDataList"
        >
          <el-table-column type="index" label="序号" width="55" fixed />
          <el-table-column prop="excelRowNum" label="excel行号" width="80" />
          <el-table-column show-overflow-tooltip prop="excelMsg" label="导入失败原因" width="240" />
          <el-table-column show-overflow-tooltip label="工单单号" prop="workNo" width="110" />
          <el-table-column show-overflow-tooltip label="工单类型" prop="module" width="110" />
          <el-table-column show-overflow-tooltip label="工单状态" prop="status" width="80" />
          <el-table-column
            show-overflow-tooltip
            label="工单质保状态"
            prop="overinsured"
            width="100"
          />
          <el-table-column show-overflow-tooltip label="质保周期" prop="warrantyDay" width="100" />
          <el-table-column show-overflow-tooltip label="报单时间" prop="createTime" width="100">
            <template #default="{ row }">
              {{ timestampToYYYYMMDDHHMMSS(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="工单等级" prop="level" width="100" />
          <el-table-column show-overflow-tooltip label="完成时间" prop="endTime" width="100">
            <template #default="{ row }">
              {{ timestampToYYYYMMDDHHMMSS(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="客户名称" prop="username" width="110" />
          <el-table-column show-overflow-tooltip label="联系人名称" prop="userPhone" width="120" />
          <el-table-column
            show-overflow-tooltip
            label="联系人手机号"
            prop="userPhone"
            width="120"
          />
          <el-table-column show-overflow-tooltip label="公司报单地址" width="300">
            <template #default="scope">
              <span>{{ scope.row.province }}&nbsp;&nbsp;</span>
              <span>{{ scope.row.area }}&nbsp;&nbsp;</span>
              <span>{{ scope.row.city }}v&nbsp;</span>
              <span>{{ scope.row.address }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="序列号" prop="code" width="160" />
          <el-table-column show-overflow-tooltip label="物料编号" prop="goodsCode" width="160" />
          <el-table-column show-overflow-tooltip label="物料型号" prop="goodsModel" width="160" />
          <el-table-column
            show-overflow-tooltip
            label="物料购买时间"
            prop="goodsBuyTime"
            width="100"
          >
            <template #default="{ row }">
              {{ timestampToYYYYMMDDHHMMSS(row.goodsBuyTime) }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="部门名称" prop="network" width="100" />
          <el-table-column
            show-overflow-tooltip
            label="部门接单时间"
            prop="networkReceivingOrdersTime"
            width="100"
          >
            <template #default="{ row }">
              {{ timestampToYYYYMMDDHHMMSS(row.networkReceivingOrdersTime) }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="工程师名称" prop="engineer" width="100" />
          <el-table-column
            show-overflow-tooltip
            label="工程师手机号"
            prop="engineerPhone"
            width="100"
          />
          <el-table-column show-overflow-tooltip label="客服名称" prop="serviceEmp" width="100" />
          <el-table-column show-overflow-tooltip label="创建人" prop="createEmp" width="100" />
          <el-table-column show-overflow-tooltip label="工单来源" prop="source" width="100" />
          <el-table-column show-overflow-tooltip label="工单描述" prop="content" width="100" />
        </el-table>

        <!-- 历史工单导入失败的数据 -->
        <el-table
          v-if="routeTitle === '历史工单导入'"
          id="el-table"
          border
          class="tableError_list"
          stripe
          resizable
          :data="dataReturned.importFailtDataList"
        >
          <el-table-column type="index" label="序号" width="55" fixed />
          <el-table-column prop="excelRowNum" label="excel行号" width="80" />
          <el-table-column show-overflow-tooltip prop="excelMsg" label="导入失败原因" width="240" />
          <el-table-column
            v-for="(item, key) in DataJson()"
            :key="key"
            show-overflow-tooltip
            :prop="item.keyName"
            :label="item.value"
            :width="
              item.value == '外部系统传单返回信息'
                ? '150'
                : item.value == 'excel行号'
                ? '80'
                : '130'
            "
          />
        </el-table>

        <!-- 部门资料导入失败的数据 -->
        <el-table
          v-if="route.name === 'networkImport'"
          id="el-table"
          border
          class="tableError_list"
          stripe
          resizable
          :data="dataReturned.importFailtDataList"
        >
          <el-table-column type="index" label="序号" width="55" fixed />
          <el-table-column prop="excelRowNum" label="excel行号" width="80" />
          <el-table-column show-overflow-tooltip prop="excelMsg" label="导入失败原因" width="240" />
          <el-table-column show-overflow-tooltip prop="name" label="部门名称" width="120" />
          <el-table-column show-overflow-tooltip prop="code" label="部门编号" width="120" />
          <el-table-column show-overflow-tooltip label="团队模式" prop="teamType" width="110" />
          <el-table-column show-overflow-tooltip label="部门模式" prop="category" width="110" />
          <el-table-column show-overflow-tooltip label="负责人名称" prop="username" width="110" />
          <el-table-column show-overflow-tooltip label="负责人手机号" prop="phone" width="120" />
          <el-table-column
            show-overflow-tooltip
            label="一级部门分类"
            prop="networkType"
            width="120"
          />
          <el-table-column
            show-overflow-tooltip
            label="二级部门分类"
            prop="twoNetworkType"
            width="120"
          />
          <el-table-column
            show-overflow-tooltip
            label="三级部门分类"
            prop="threeNetworkType"
            width="120"
          />
          <el-table-column
            show-overflow-tooltip
            label="部门机构名称"
            prop="networkAgency"
            width="120"
          />
          <el-table-column show-overflow-tooltip label="部门地址" width="300">
            <template #default="scope">
              <span>{{ scope.row.province }}&nbsp;&nbsp;</span>
              <span>{{ scope.row.area }}&nbsp;&nbsp;</span>
              <span>{{ scope.row.city }}&nbsp;</span>
              <span>{{ scope.row.address }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 序列号档案导入失败的数据 -->
        <el-table
          v-if="route.name === 'codeExcelImport'"
          id="el-table"
          border
          class="tableError_list"
          stripe
          resizable
          :data="dataReturned?.importFailtDataList"
        >
          <el-table-column type="index" label="序号" width="55" fixed :align="'center'" />
          <el-table-column prop="excelRowNum" label="excel行号" width="80" />
          <el-table-column show-overflow-tooltip prop="excelMsg" label="导入失败原因" width="240" />
          <el-table-column show-overflow-tooltip label="序列号" prop="code" width="130" />
          <el-table-column show-overflow-tooltip label="创建时间" prop="createTime" width="140">
            <template #default="i">
              {{ i.row.createTime ? timestampToYYYYMMDDHHMMSS(i.row.createTime) : '' }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="type" label="序列号类型" width="120" />
          <el-table-column show-overflow-tooltip label="物料编号" prop="goodsCode" width="110" />
          <el-table-column show-overflow-tooltip label="物料型号" prop="goodsModel" width="110" />
          <el-table-column show-overflow-tooltip label="物料规格" prop="goodsSpec" width="110" />
          <el-table-column show-overflow-tooltip label="生产日期" prop="produceDate" width="110" />
          <el-table-column show-overflow-tooltip label="序列号激活状态" prop="activa" width="110" />
          <el-table-column show-overflow-tooltip label="激活时间" prop="activeTime" width="140" />
          <el-table-column show-overflow-tooltip label="序列号质保状态" prop="status" width="110" />
          <el-table-column show-overflow-tooltip label="登记日期" prop="registerTime" width="130" />
          <el-table-column show-overflow-tooltip label="质保周期" prop="warrantyDay" width="100" />
          <el-table-column show-overflow-tooltip label="登记公司姓名" prop="username" width="100" />
          <el-table-column show-overflow-tooltip label="登记公司地址" width="140">
            <template #default="{ row }">
              {{ `${row.province}-${row.city}-${row.area}-${row.address}` }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 物料BOM导入失败的数据 -->
        <el-table
          v-if="route.name === 'goodBomImport'"
          id="el-table"
          border
          class="tableError_list"
          stripe
          resizable
          :data="dataReturned?.importFailtDataList"
        >
          <el-table-column type="index" label="序号" width="55" fixed :align="'center'" />
          <el-table-column prop="excelRowNum" label="excel行号" width="80" />
          <el-table-column show-overflow-tooltip prop="excelMsg" label="导入失败原因" width="240" />
          <el-table-column show-overflow-tooltip label="物料编号" prop="goodsCode" width="130" />
          <el-table-column
            show-overflow-tooltip
            label="物料名称"
            prop="goodsName"
            width="140"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="物料类型"
            prop="goodsTypeStr"
            width="140"
          ></el-table-column>
          <el-table-column show-overflow-tooltip prop="goodsSpec" label="物料规格" width="120" />
          <el-table-column
            show-overflow-tooltip
            label="物料备注（组合件）"
            prop="goodsRemark"
            width="140"
          />
          <el-table-column
            show-overflow-tooltip
            label="物料子件序列号"
            prop="boomGoodsCode"
            width="110"
          />
          <el-table-column
            show-overflow-tooltip
            label="物料子件类型"
            prop="boomGoodsType"
            width="110"
          >
            <template #default="{ row }">{{ row.boomGoodsType === 1 ? '成品' : '物料' }}</template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="物料子件名称"
            prop="boomGoodsName"
            width="110"
          />
          <el-table-column
            show-overflow-tooltip
            label="物料子件规格"
            prop="boomGoodsSpec"
            width="110"
          />
          <el-table-column
            show-overflow-tooltip
            label="物料子件数量"
            prop="boomGoodsQty"
            width="140"
          />
          <el-table-column
            show-overflow-tooltip
            label="物料子件备注"
            prop="boomGoodsRemark"
            width="110"
          />
        </el-table>
      </div>
      <div
        v-if="dataReturned && dataReturned.end && dataReturned.importFailtDataList.length > 0"
        class="footer_btn_group"
      >
        <h-button type="primary" @click="exportToExcel">导出全部错误信息</h-button>
        <h-button @click="onClearFailInfo">清空错误信息</h-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, watch } from 'vue'
  import { UploadFilled } from '@element-plus/icons-vue'
  import type { UploadInstance, UploadRawFile, UploadProps } from 'element-plus'
  import { ElMessage, genFileId } from 'element-plus'
  import { initWebSocket, closeWebSocket } from '@/utils/socket'
  import { downloadExcelTemplate } from '@/utils/download'
  import {
    goodsExcelImport,
    userExcelImport,
    networkEmpImport,
    networkImport,
    codeImport,
    orderImport,
    historyOrderImport,
    goodBOMImport,
  } from '@/api/upload'
  import moment from 'moment'
  import FileSaver from 'file-saver'
  import * as XLSX from 'xlsx'
  import * as _ from 'lodash'
  import { useRoute, useRouter } from 'vue-router'
  import { UploadResult } from './types'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { useExcel, useGetFailDataExcelExport } from '@/services/pages/excel'
  import routeComponentName from '@/config/route-component-name'
  import { HMessageBox } from '@/components/common/message'

  defineOptions({
    name: routeComponentName.common.import,
  })

  const { timestampToYYYYMMDDHHMMSS } = useExcel()
  const {
    getOrderFailDataExcelExport,
    getSnCodeFailDataExcelExport,
    getNetworkFailDataExcelExport,
    gethistoryFailDataExcelExport,
    DataJson,
    getEngineerFailDataExcelExport,
    getGoodBomImportFailDataForExcelExport,
    getGoodImportFailDataForExcelExport,
  } = useGetFailDataExcelExport()

  // 标签状态
  const tagsViewStore = useTagsViewStore()

  const onClearFailInfo = () => {
    stopSyncProgressTimer()
    dataReturned.value = null
    errorList.value = []
    syncProgress.value = 0
  }

  // 激活的路由对象
  const route = useRoute()
  const router = useRouter()
  const fileList = ref([]) // 上传的文件
  const upload = ref<UploadInstance>()
  // const dataReturned = ref<UploadResult | null>(null)
  const dataReturned: any = ref(null)

  const onRemoveFileBtnClick = () => {
    fileList.value = []
    resetState()
  }

  // 超出限制时执行，覆盖前一个文件
  const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value.handleStart(file)
    resetState()
  }

  const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    fileList.value = []
    dataReturned.value = null
    fileList.value = uploadFiles
  }

  const isUploading = ref(false)

  /**
   * 确认上传按钮点击事件
   */
  const onConfirmUploadBtnClick = _.debounce(async () => {
    if (fileList.value.length > 0) {
      resetState()
      isUploading.value = true
      let uuid = new Date().getTime()
      dataReturned.value = null
      initWebSocket(funProgress, `/ws/progress/${uuid}`)
      startSyncProgressTimer()

      if (route.name === 'orderExcelImport') {
        orderImport(uuid, fileList.value[0].raw).then((res) => {
          if (res) {
            if (!res.data.success) {
              isUploading.value = false
              HMessageBox.error(res.data.message)
            }
          }
        })
      }
      if (route.name === 'orderhistoryExcelImport') {
        historyOrderImport(uuid, fileList.value[0].raw).then((res) => {
          if (res) {
            if (!res.data.success) {
              isUploading.value = false
              HMessageBox.error(res.data.message)
            }
          }
        })
      }
      if (route.name === 'goodsExcelImport') {
        goodsExcelImport(fileList.value[0].raw, goodType.value, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              isUploading.value = false
              HMessageBox.error(res.data.message)
            }
          }
        })
      } else if (route.name === 'userExcelImport') {
        userExcelImport(fileList.value[0].raw, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              isUploading.value = false
              HMessageBox.error(res.data.message)
            }
          }
        })
      } else if (route.name === 'empExcelImport') {
        networkEmpImport(fileList.value[0].raw, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              isUploading.value = false
              HMessageBox.error(res.data.message)
            }
          }
        })
      } else if (route.name === 'networkImport') {
        networkImport(fileList.value[0].raw, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              isUploading.value = false
              HMessageBox.error(res.data.message)
            }
          }
        })
      } else if (route.name === 'codeExcelImport') {
        codeImport(fileList.value[0].raw, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              isUploading.value = false
              HMessageBox.error(res.data.message)
            }
          }
        })
      } else if (route.name === 'goodBomImport') {
        const res = await goodBOMImport(fileList.value[0].raw, uuid)
        if (res && res.data.code !== 20000) {
          isUploading.value = false
          HMessageBox.error(res.data.message)
        }
      }
    }
  }, 600)

  const errorList = ref<UploadResult['importFailtDataList']>([])

  // 同步进度
  const syncProgress = ref(0)

  // 进度同步定时器
  const syncProgressTimer = ref<NodeJS.Timeout | null>(null)

  /**
   * 开启定时器（进度同步定时器）
   */
  const startSyncProgressTimer = () => {
    syncProgressTimer.value = setInterval(() => {
      syncProgress.value = Number((syncProgress.value + 0.01).toFixed(2))
      if (dataReturned.value && !dataReturned.value.end && syncProgress.value >= 99.99) {
        stopSyncProgressTimer()
      }
    }, 1000)
  }

  /**
   * 关闭定时器（进度同步定时器）
   */
  const stopSyncProgressTimer = () => {
    if (syncProgressTimer.value) {
      clearInterval(syncProgressTimer.value)
    }
  }

  // TODO 类型
  const funProgress = (msg: UploadResult) => {
    dataReturned.value = {
      currentProgress: msg.currentProgress,
      end: msg.end,
      message: msg.message,
      totalCount: msg.totalCount,
      importFailtDataList: [],
    }
    errorList.value.push(...msg.importFailtDataList)
    if (Number(msg.currentProgress) === 100 && msg.end) {
      stopSyncProgressTimer()
      errorList.value.sort((a, b) => {
        return a.excelRowNo - b.excelRowNo
      })
      dataReturned.value.importFailtDataList = _.cloneDeep(errorList.value).slice(0, 8)

      closeWebSocket()
      isUploading.value = false
    }
  }

  // 准备要导出的数据   https://blog.csdn.net/qq_40036754/article/details/117228315
  const exportToExcel = () => {
    // TODO 未来其他页面导入错误信息的下载方案都要改成序列号档案导入的这种
    // 因为现在的错误信息只显示前8条，所以以前的方式只能下载前8条错误信息
    const arr = [
      'codeExcelImport',
      'networkImport',
      'orderExcelImport',
      'orderhistoryExcelImport',
      'empExcelImport',
      'goodBomImport',
      'goodsExcelImport',
    ]
    if (arr.includes(route.name as string)) {
      const getDataExcelExport = {
        orderExcelImport: getOrderFailDataExcelExport,
        codeExcelImport: getSnCodeFailDataExcelExport,
        networkImport: getNetworkFailDataExcelExport,
        orderhistoryExcelImport: gethistoryFailDataExcelExport,
        empExcelImport: getEngineerFailDataExcelExport,
        goodBomImport: getGoodBomImportFailDataForExcelExport,
        goodsExcelImport: getGoodImportFailDataForExcelExport,
      }
      const worksheet = XLSX.utils.aoa_to_sheet(
        getDataExcelExport[route.name as string](errorList.value),
      )
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
      XLSX.writeFile(workbook, `导入失败数据_${moment(new Date()).format('YYYYMMDD')}.xlsx`)
    } else {
      // 手机号，身份证号等会默认使用科学计数法表示，则需要这样设置
      const wb = XLSX.utils.table_to_book(document.querySelector('#el-table'), { raw: true })
      const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          `导入失败数据_${moment(new Date()).format('YYYYMMDD')}.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') {
          // 保存失败
        }
      }
    }
  }

  // 物料类型
  const goodType = ref(1)

  const routeTitle = computed(() => route.meta.title as string)

  /**
   * 取消按钮点击事件
   */
  const onCancelBtnClick = () => {
    fileList.value = []
    dataReturned.value = null
    useTagsViewStore().delView(route.path)
    switch (route.name as string) {
      case 'goodsExcelImport':
        router.push('/commodity/commodi')
        break
      case 'userExcelImport':
        router.push('/user/list')
        break
      case 'empExcelImport':
        router.push('/net/empList')
        break
      case 'orderExcelImport':
        router.push('/order/list')
        break
      case 'orderhistoryExcelImport':
        router.push('/order/history')
        break
      case 'networkImport':
        router.push('/net/list')
        break
      case 'codeExcelImport':
        router.push('/code/list')
        break
      case 'godBomImport':
        router.push({ name: 'goodBomImport' })
        break
    }
  }

  /**
   * 清空所有状态并关闭websocket
   */
  const resetState = () => {
    syncProgress.value = 0
    dataReturned.value = null
    errorList.value = []
    closeWebSocket()
    stopSyncProgressTimer()
  }

  watch(
    () => route,
    (value) => {
      // if (value.name === 'orderExcelImport' && value.meta.title === '工单资料导入') {
      // getCustomerOptionsFn('')
      // getOrderTypeOptionsFn('')
      // }
      if (value.name === 'goodsExcelImport' && value.name === 'goodsExcelImport') {
        goodType.value = Number(route.query.type) || 1
      }
    },
    { immediate: true, deep: true },
  )

  watch(
    () => tagsViewStore.getReloadPages,
    (value) => {
      if (value.includes(route.path)) {
        fileList.value = []
        resetState()
      }
    },
    { immediate: true, deep: true },
  )

  onMounted(() => {
    resetState()
  })
</script>

<style scoped lang="scss">
  @import './ExcelImport.scss';
</style>
